<template lang="pug">
.chartnrw-wrapper
  h6.chart-title 产销差水量与产销差比率对比
  ECharts.bar-chart(
    ref='barChart'
    auto-resize
    :options="options"
    @click="selectBar")
  span.btn-export.iconfont.icon-export(
    title='导出'
    @click="fileEvent('/pn/dpa/stat/nrw/export')")
</template>
<script>
/**
 * @name PartionInfo 产销差水量与无收益水量对比柱状图
 * @author 王锐锋 <wangrf@gddxit.com>
 * @description 用于展示产销差与无收益水量对比柱状图
 *参数：
 */
export default {
  props: {
    areaId: Number | Boolean,
    timeRange: Array,
    selectedData: Object
  },
  data () {
    return {
      options: {
        color: ['#0000EE', '#CD0000'],
        tooltip: {
          trigger: 'axis',
          // formatter: '{b}<br /> <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#0000EE;"></span> {a0}：{c0} m³<br/> <span style="display:inline-block;margin-right:5px;border-radius:10px;width:10px;height:10px;background-color:#CD0000;"></span> {a1}：{c1} %',
          formatter: (param) => {
            let format = ''
            param.forEach((item, index) => {
              if (index === 0) format = param[0].name + '<br> &nbsp;'
              format = format.concat(item.marker + item.seriesName + '：' + (this.formatValue(item.value) || '-') + ' ' + (item.seriesName === '产销差比率' ? '%' : 'm³/h') + '<br>')
            })
            return format
          },
          axisPointer: {
            type: 'cross',
            label: {
              show: false
            }
          },
          textStyle: {
            fontSize: 12,
            fontWeight: 'bold',
            fontFamily: 'Microsoft YaHei'
          }
        },
        grid: [
          {left: 100, right: 100, y: '15%', height: '65%'}
        ],
        legend: {
          data: ['产销差水量', '产销差比率'],
          y: 'bottom',
          itemWidth: 14
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            axisTick: {show: false},
            data: []
          }
        ],
        yAxis: [
          {
            type: 'value',
            scale: true,
            name: '产销差水量(m³)',
            min: 0,
            boundaryGap: [0.2, 0.2]
          },
          {
            type: 'value',
            scale: true,
            name: '产销差比率(%)',
            min: 0,
            boundaryGap: [0.2, 0.2]
          }
        ],
        series: [
          {
            name: '产销差水量',
            type: 'bar',
            barWidth: '40%',
            barGap: '1%',
            data: [],
            markPoint: {
              symbol: 'pin',
              symbolSize: (value, params) => {
                let width = this.formatValue(value).length * 14
                width = (width < 40) ? 40 : width
                return [width, 40]
              },
              label: {
                formatter: ({seriesName, name, value}) => {
                  return `${this.formatValue(value) || '-'}`
                }
              },
              data: [
                {type: 'max', name: '最大值'},
                {type: 'min', name: '最小值'}
              ]
            }
            // markPoint: {
            //   symbolSize: 1,
            //   symbolOffset: [0, '50%'],
            //   label: {
            //     normal: {
            //       offset: [0, -15],
            //       formatter: ({seriesName, name, value}) => {
            //         return `${seriesName}${name}：${(this.formatValue(value) || '-') + ' m³'}`
            //       },
            //       backgroundColor: 'rgba(0,0,0,0.7)',
            //       borderRadius: 15,
            //       padding: [4, 10],
            //       lineHeight: 15,
            //       height: 15,
            //       distance: 20,
            //       color: '#fff',
            //       textBorderColor: '#000',
            //       textBorderWidth: 1,
            //       fontSize: 12,
            //       fontWeight: 'bold',
            //       fontFamily: 'Microsoft YaHei'
            //     }
            //   },
            //   data: [
            //     {type: 'max', name: '最大值'},
            //     {type: 'min', name: '最小值'}
            //   ]
            // }
          },
          {
            name: '产销差比率',
            type: 'bar',
            barWidth: '40%',
            yAxisIndex: '1',
            barGap: '15%',
            data: [],
            markPoint: {
              symbol: 'pin',
              symbolSize: (value, params) => {
                let width = this.formatValue(value).length * 14
                width = (width < 40) ? 40 : width
                return [width, 40]
              },
              label: {
                formatter: ({seriesName, name, value}) => {
                  return `${this.formatValue(value) || '-'}`
                }
              },
              data: [
                {type: 'max', name: '最大值'},
                {type: 'min', name: '最小值'}
              ]
            }
            // markPoint: {
            //   symbolSize: 1,
            //   symbolOffset: [0, '50%'],
            //   label: {
            //     normal: {
            //       offset: [0, -15],
            //       formatter: ({seriesName, name, value}) => {
            //         return `${seriesName}${name}：${(this.formatValue(value) || '-') + ' %'}`
            //       },
            //       backgroundColor: 'rgba(0,0,0,0.7)',
            //       borderRadius: 20,
            //       padding: [4, 10],
            //       lineHeight: 20,
            //       height: 20,
            //       distance: 20,
            //       opacity: 50,
            //       color: '#fff',
            //       textBorderColor: '#000',
            //       textBorderWidth: 1,
            //       fontSize: 12,
            //       fontWeight: 'bold',
            //       fontFamily: 'Microsoft YaHei'
            //     }
            //   },
            //   data: [
            //     {type: 'max', name: '最大值'},
            //     {type: 'min', name: '最小值'}
            //   ]
            // }
          }
        ]
      }
    }
  },
  methods: {
    getData () {
      this.$get({
        url: `/pn/dpa/stat/nrw`,
        params: {
          // 'areaId': this.areaId,
          'startTime': this.timeRange[0].getTime(),
          'endTime': this.timeRange[1].getTime()
        }
      }).then((data) => {
        this.options.series = this.options.series.map((serie, index) => {
          return {
            ...serie,
            name: data.series.find(item => (item.name === serie.name)).name,
            data: data.series.find(item => (item.name === serie.name)).data
          }
        })
        this.options.legend.data = data.series.map(item => item.name)
        this.options.xAxis[0].data = data.xAxis.map(item => {
          const chsName = data.relation.find(area => {
            return area.value === item
          })
          return chsName ? chsName.label : item
        })
        this.$nextTick(() => {
          this.highlightBar(this.selectedData.seriesIndex, this.selectedData.dataIndex)
        })
      })
    },
    selectBar (params) {
      this.$emit('selectAreaPie', params)
    },
    highlightBar (seriesIndex, dataIndex) {
      this.$refs.barChart.dispatchAction({
        type: 'highlight',
        seriesIndex: 0,
        dataIndex
      })
      this.$refs.barChart.dispatchAction({
        type: 'highlight',
        seriesIndex: 1,
        dataIndex
      })
      this.$refs.barChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 0,
        dataIndex
      })
      this.$refs.barChart.dispatchAction({
        type: 'showTip',
        seriesIndex: 1,
        dataIndex
      })
    },
    formatValue (data) {
      return (data === null || data === undefined) ? null : parseFloat(data).toFixed(3)
    },
    fileEvent (url, filterBy) {
      this.$get({
        url,
        params: {
          'startTime': this.timeRange[0].getTime(),
          'endTime': this.timeRange[1].getTime()
        }
      }).then((res) => {
      // 生成a标签，模拟click下载files
        if (!res.data) {
          this.$alert('导出失败！')
          return
        }
        let a = document.createElement('a')
        a.href = `/api/dxbase/download/${res.data.shortUrl}`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        event.stopPropagation()
        event.preventDefault()
      })
    }
  },
  mounted () {
    this.getData()
  }
}
</script>

<style lang="sass" scoped>
.chartnrw-wrapper
  width: 100%
  height: 100%
  display: flex
  flex-direction: column
  position: relative
  .btn-export
    color: #a0a0a0
    font-size: 20px
    position: absolute
    right: 3px
    top: 40px
    cursor: pointer
  h6
    text-align: center
    font-weight: bold
    font-size: 16px
    margin: 0
    margin-top: 5px
  .bar-chart
    width: 100%
    flex: 1
    background-color: #fff
</style>
